<template>
    <view class="content">
        <show-modal></show-modal>
        <!-- <cu-custom bgColor="bg-gradual-red" :isBack="true">
            <block slot="backText">返回</block>
            <block slot="content">{{detailData.name}}</block>
        </cu-custom> -->

        <view class="box">
            <view class="with-fun">
                <image style="width: 100%;" v-if="detailData.video == null || detailData.video == ''"
                    :src="detailData.pic" mode="widthFix" @click="long_tap(detailData.pic)">
                </image>
                <video style="width: 100%;" v-if="detailData.video != null && detailData.video != ''"
                    :src="detailData.video" :poster="detailData.pic" mode="widthFix"
                    @longtap="saveVideo(detailData.video)"></video>
            </view>

            <view class="solids-bottom bg-white padding-xs flex align-center">
                <view class="flex-sub">
                    <view class="solid-bottom text-xl padding">
                        <text class="text-black text-bold">
                            {{detailData.name}}
                        </text>
                    </view>
                    <view class="padding">
                        <text class="xl text-orange margin-right-xs" :class="'cuIcon-timefill'"></text>
                        {{detailData.views}} 次观看
                        <text class="xl text-orange margin-right-xs margin-left-sm" :class="'cuIcon-favorfill'"></text>
                        {{detailData.collects}} 次收藏
                    </view>
                </view>
            </view>

            <!-- <view class="solids-bottom bg-white padding-xs flex align-center">
                <button @click="chooseVideo">chooseVideo</button>
                <button open-type="uploadDouyinVideo">uploadDouyinVideo</button>
            </view> -->

            <view class="cu-list menu-avatar">
                <view class="cu-item" v-if="detailData.creatorId != 1374785249722953730">
                    <view class="cu-avatar round xs" :style="'background-image:url(' +detailData.avatar +');'"></view>
                    <view class="content flex-sub">
                        <view>{{detailData.nickname}}</view>
                        <view class="text-gray text-sm flex justify-between">
                            {{detailData.createTime}}
                        </view>
                    </view>
                </view>
                <view class="cu-item" v-if="detailData.creatorId == 1374785249722953730">
                    <view class="flex-treble padding-left">
                        <view>内容来源于网络投稿，如有侵权</view>
                        <view>请联系我们删除</view>
                    </view>
                    <view class="flex-sub round xs">
                        <button class="cu-btn xs bg-red" open-type="contact"> 联系我们 </button>
                    </view>
                </view>
            </view>

            <view class="cu-bar bg-white solid-bottom">
                <view class="action">
                    <text class="cuIcon-titles text-red"></text> 月龄
                </view>
            </view>
            <view class="solids-bottom bg-white padding-xs flex align-center">
                <view class="flex-sub">
                    <view class="padding">
                        {{detailData.listMonth[0].cateName}}
                    </view>
                </view>
            </view>


            <view class="cu-bar bg-white solid-bottom">
                <view class="action">
                    <text class="cuIcon-titles text-red"></text> 食材清单
                </view>
            </view>
            <view class="solids-bottom bg-white padding-xs flex align-center">
                <view class="flex-sub">
                    <view class="padding">
                        <text class="margin-right-xs" v-for="(item,index) in detailData.listMaterial" :key="index"
                            selectable="true">
                            {{item.name}}{{item.quantity}}{{item.unit}},
                        </text>
                    </view>
                </view>
            </view>

            <view class="cu-bar bg-white solid-bottom">
                <view class="action">
                    <text class="cuIcon-titles text-red"></text> 制作步骤
                </view>
            </view>

            <view class="bg-white padding-xs flex align-center" v-for="(item,index) in detailData.listStep"
                :key="index">
                <view class="flex-sub">
                    <view class="text-xl padding">
                        <text class="text-black text-bold">
                            步骤 {{index + 1}}
                        </text>
                        <text class="text-gray"> / {{detailData.listStep.length}}</text>
                    </view>

                    <view class="cu-card dynamic" :class="'no-card'">
                        <view class="cu-item shadow">
                            <text class="padding" v-if="item.description" selectable="true">
                                {{item.description}}
                            </text>
                            <view class="grid flex-sub padding" :class="'col-3 grid-square'">
                                <!-- <view class="bg-img only-img" :style="'background-image:url(' +item.imageUrl +');'">
                                </view> -->
                                <image style="width: 100%;" :src="item.imageUrl" mode="widthFix"
                                    @click="long_tap(item.imageUrl)"></image>
                            </view>
                        </view>
                    </view>
                </view>
            </view>


            <view class="cu-bar bg-white solid-bottom">
                <view class="action">
                    <text class="cuIcon-titles text-red"></text> 温馨提示
                </view>
            </view>
            <view class="solids-bottom bg-white padding-xs flex align-center">
                <view class="flex-sub">
                    <view class="padding">
                        <text class="margin-right-xs" selectable="true">
                            {{detailData.description}}
                        </text>
                    </view>
                </view>
            </view>


            <view class="solid-bottom text-xl padding margin-bottom-xl">
                美食家
            </view>

            <view class="cu-bar bg-white tabbar border shop foot">
                <button class="action" open-type="share">
                    <view class="cuIcon-share text-green"></view>分享
                </button>
                <view class="action" :class="detailData.isCollect==1?'text-orange':'text-black'" @click="collect">
                    <view :class="detailData.isCollect==1?'cuIcon-favorfill':'cuIcon-favor'" class="cuIcon-favor">
                    </view>
                    收藏
                </view>
                <button class="action" @click="downloadVideo" @longtap="reDownloadVideo">
                    <view class="cuIcon-down text-black"></view>生成视频
                </button>
                <button :class="canPublish?'bg-red submit':'bg-gray submit'"
                    open-type="uploadDouyinVideo">发布到抖音</button>
            </view>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                // 导航栏
                config: {
                    title: "详情页", //title
                    bgcolor: "#c1a379", //背景颜色
                    type: 1, //type 1，3胶囊 2，4无胶囊模式
                    linear: true, //是为开启下滑渐变
                },
                detailId: 0,
                detailData: {
                    listMonth: [{
                        "cateName": ""
                    }],
                    listMaterial: [],
                    listStep: [],
                },
                isCard: true,
                videoPath: "",
                canPublish: false
            }
        },
        onLoad(e) {
            console.log("详情页", e)
            this.detailId = e.id;
            uni.setStorageSync("detail_id", e.id);
            this.getDetail();
        },
        mounted() {
            console.log('详情页 mounted')
            let that = this;
            uni.checkSession({
                success: function(t) {
                    console.log("没过期");
                },
                fail: function() {
                    console.log("过期了");
                    uni.showLoading({
                        mask: true,
                        title: '授权登录中...',
                    })
                    let baseAuthCode = uni.getStorageSync("baseAuthCode");
                    if (!baseAuthCode) {
                        that.$api.baseToken().then(() => {
                            uni.hideLoading();
                        });
                        return;
                    }
                    that.$api.baseLogin(baseAuthCode).then(() => {
                        uni.hideLoading();
                        that.getDetail();
                    });;
                }
            });
        },
        methods: {
            chooseVideo() {
                console.log("chooseVideo ");
                uni.chooseVideo({
                    sourceType: ["album", "camera"],
                    compressed: true,
                    success: (res) => {
                        let {
                            duration,
                            width,
                            height,
                            size
                        } = res;
                        this.videoPath = res.tempFilePath
                        this.description =
                            `视频时长：${duration}s; 视频宽度：${width}px; 视频高度：${height}px; 视频大小：${size}B; 临时路径：${res.tempFilePath}`
                        console.log(this.description);
                    },
                    fail: (err) => {
                        let errType = err.errMsg.includes("chooseVideo:fail cancel") ?
                            "取消选择" :
                            "选择失败";
                        uni.showModal({
                            title: errType,
                            content: err.errMsg,
                            showCancel: false,
                        });
                    },
                });
            },
            saveVideo(save_url) {
                this.$showModal({
                    content: '确定保存视频到相册吗？',
                    confirmText: "保存",
                    cancelText: "取消",
                    success: (res) => {
                        if (res.confirm) {
                            console.log('用户点击确定');
                            uni.showLoading({
                                title: '加载中...',
                                mask: true
                            });
                            uni.downloadFile({
                                url: save_url,
                                success: (res) => {
                                    const that = this
                                    if (res.statusCode === 200) {
                                        // 保存视频到手机相册
                                        uni.saveVideoToPhotosAlbum({
                                            filePath: res.tempFilePath,
                                            success: function() {
                                                // 成功提示
                                                uni.showToast({
                                                    title: '保存成功',
                                                    icon: 'success'
                                                })
                                            }
                                        })
                                    }
                                },
                                fail() {
                                    uni.hideLoading()
                                }
                            })
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                });
            },
            long_tap(save_url) {
                console.log("long_tap");
                uni.previewImage({
                    urls: [save_url], //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
                    current: "", // 当前显示图片的http链接，默认是第一个
                    success: function(res) {},
                    fail: function(res) {},
                    complete: function(res) {},
                    //长按保存到本地
                    longPressActions: {
                        itemList: ["保存图片到本地"],
                        success: (data) => {
                            if (data.tapIndex == 0) {
                                let url = save_url;
                                uni.saveImageToPhotosAlbum({
                                    filePath: url,
                                    success: (res) => {
                                        uni.showToast({
                                            title: "已存至系统相册",
                                            icon: "success",
                                        });
                                    },
                                    fail: (res) => {
                                        uni.showToast({
                                            title: "保存失败",
                                            icon: "error",
                                        });
                                    },
                                });
                            }
                        },
                        fail: function(err) {
                            console.log(err.errMsg);
                        },
                    },
                });
            },

            getDetail() {
                let data = {
                    "bookId": this.detailId
                }
                this.$api.bookDetail(data).then((res) => {
                    this.loading = false;
                    console.log("请求详情成功", res.data);
                    this.detailData = res.data;
                    uni.setStorageSync("detail_name", res.data.name);
                    uni.setStorageSync("detail_pic", res.data.pic);
                }).catch((err) => {
                    this.loading = false;
                    console.error('request fail', err);
                })
            },
            collect() {
                let data = {
                    "bookId": this.detailId
                }
                this.$api.collect(data).then((res) => {
                    this.loading = false;
                    if (res.data) {
                        console.log("收藏成功", res.data);
                        this.detailData.isCollect = 1;
                        uni.showToast({
                            title: "收藏成功",
                            icon: "success"
                        })
                    } else {
                        console.log("取消收藏成功", res.data);
                        this.detailData.isCollect = 0;
                        uni.showToast({
                            title: "取消收藏成功",
                            icon: "success"
                        })
                    }
                }).catch((err) => {
                    this.loading = false;
                    console.error('request fail', err);
                })
            },
            reDownloadVideo() {
                this.detailData.video = "";
                this.downloadVideo();
            },
            downloadVideo() {
                if (!this.detailData.video) {
                    let userInfo = uni.getStorageSync('userInfo');
                    console.log("缓存中用户信息", userInfo);
                    if (userInfo.memberInfo.phone != "13609245992") {
                        uni.showModal({
                            title: "",
                            content: "非视频不可缓存",
                            showCancel: false,
                        });
                        return;
                    }
                    
                    uni.showLoading({
                        title: '正在生成...',
                        mask: true
                    });
                    
                    let data = {
                        bookId: this.detailData.id,
                        imageList: []
                    };
                    this.detailData.listStep.forEach((item, index) => {
                        data.imageList.push(item.imageUrl);
                    });
                    console.log("请求createMp4", data);
                    this.$api.createMp4(data).then((res) => {
                        console.log("请求createMp4成功", res.data);
                        uni.showToast({
                            title: "生成成功",
                            icon: "success"
                        });
                    }).catch((err) => {
                        uni.showToast({
                            title: "异步处理中",
                            icon: "none"
                        });
                        console.error('request fail', err);
                    })
                    return;
                }
                uni.showLoading({
                    title: '加载中...',
                    mask: true
                });

                uni.downloadFile({
                    url: this.detailData.video,
                    success: (res) => {
                        const that = this
                        if (res.statusCode === 200) {
                            this.videoPath = res.tempFilePath;
                            this.canPublish = true;
                            uni.showToast({
                                title: "缓存成功",
                                icon: "success",
                            });
                        }
                    },
                    fail() {
                        uni.hideLoading();
                    }
                })
            }
        },
        onShareAppMessage: function(t) {
            return t.from, {
                title: uni.getStorageSync("detail_name"),
                path: "/pages/home/detail?id=" + uni.getStorageSync("detail_id") + "&openid=" + uni
                    .getStorageSync("share_openid"),
                imageUrl: uni.getStorageSync("detail_pic")
            };
        },
        onReady() {
            let _that = this;
            this.$mp.page.onUploadDouyinVideo = function(uploadOptions) {
                // 通过 uploadOptions 可以拿到 button target 上的一些信息
                console.log("onUploadDouyinVideoOptions: ", uploadOptions);
                if (!_that.canPublish) {
                    uni.showToast({
                        title: "请先缓存视频",
                        icon: "none",
                    });
                    return {};
                }
                uni.showLoading({
                    title: '加载中...',
                    mask: true
                });

                // 返回值（文档中称之为 uploadParams）将被当作发布参数传入视频发布器，发布视频
                return {
                    videoPath: _that.videoPath,
                    titleConfig: {
                        title: _that.detailData.description + "更多请戳左下角",
                        hashtagMarkers: [{
                            hashtag: "美味辅食"
                        }, {
                            hashtag: "营养辅食"
                        }, {
                            hashtag: "辅食宝典"
                        }]
                    },
                    // extra: {
                    //     anchor: {
                    //         anchorType: "app",
                    //         title: "每日推荐-辅食宝典"
                    //     }
                    // },
                    success: function(res) {
                        // 只有当发布成功且挂载成功时，res 才会有 videoId
                        console.log("success", res);

                        uni.showToast({
                            title: "发布成功",
                            icon: "success",
                        });
                    },
                    fail: function(err) {
                        console.log("fail: ", err.errMsg);
                        uni.showToast({
                            title: "发布失败",
                            icon: "error",
                        });
                    },
                    complete: function(callback) {
                        console.log("complete: ", callback);
                        uni.hideLoading();
                    },
                };
            }
        }
    }
</script>
<style>
    .box {
        margin: 0;
    }

    .box view.cu-bar {
        margin-top: 20upx;
    }
</style>
